<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2020-06-27 14:06:58
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-05-05 08:55:39
 */

namespace Common\Helpers;

use Common\Exception\BaseException;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class LoggingHelper
{

    public static function get(string $name = 'app')
    {
        try {
            return ApplicationContext::getContainer()->get(LoggerFactory::class)->get($name);
        } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) {
            throw new BaseException(405,$e->getMessage());
        }
    }

    public static function mkDirs($catalogue): bool
    {
        if (!file_exists($catalogue)) {
            self::mkDirs(dirname($catalogue));
            mkdir($catalogue, 0777);
            @chmod($catalogue, 0777);
        }

        return true;
    }


    public static function writeLog($device, $path, $mark, $content = []): bool|int
    {
        $basePath = BASE_PATH . "/Log/" . ucwords($device)  . date('/Y/m/d/') . $path . '.log';
        self::mkDirs(dirname($basePath));
        $time = date('m/d H:i:s');
        // 加入内存使用情况
        $memoryInit = memory_get_usage() / 1024 / 1024;
        $contentTxt = json_encode($content);
        return file_put_contents($basePath, "\r\n" . $time . '-' . $mark . ':' . $contentTxt, FILE_APPEND);
    }
}
